#pragma once

#include <iostream>
#include <set>
#include <string>
#include <cstdio>

const int line_size = 1024;

class CommandExec
{
public:
    CommandExec()
    {
        _white_list.insert("ls");
        _white_list.insert("ls -l");
        _white_list.insert("pwd");
        _white_list.insert("ll");
        _white_list.insert("touch");
        _white_list.insert("who");
        _white_list.insert("whoami");
    }

    bool safecheck(const std::string &cmdstr)
    {
        auto iter = _white_list.find(cmdstr);
        return iter == _white_list.end() ? false : true;
    }

    std::string Execute(std::string cmdstr)
    {
        if (!safecheck(cmdstr))
        {
            return std::string(cmdstr + " 不支持");
        }

        FILE *fp = popen(cmdstr.c_str(), "r");
        if (fp == nullptr)
        {
            return std::string("failed");
        }

        char buffer[line_size];
        std::string result;
        while (true)
        {
            char *ret = ::fgets(buffer, sizeof(buffer), fp);
            if (!ret)
                break;
            result += ret;
        }

        pclose(fp);
        return result.empty() ? std::string("Done") : result;
    }

private:
    std::set<std::string> _white_list;
};